import Taro from "@tarojs/taro";
import _ from 'loadsh';
import {getStorePreImgUrI} from "./storage";

export function padImgURI(endImgURL: string): string {
  const preImgURI: string = getStorePreImgUrI();
  if (!preImgURI) return '无效的图片前缀';
  return endImgURL ? preImgURI + endImgURL : require('@/static/images/order/temp.png');
}

export function transferDay(day: number, type: string = '星期'): string {
  const dayList = ['日', '一', '二', '三', '四', '五', '六'];
  return type + dayList[day];
}


export function decodeURIByRouteParams(s: string): string {
  return decodeURIComponent(Taro.getCurrentInstance().router.params[s]);
}

export interface IModelToast {
  title?: string,
  icon?: 'success' | 'error' | 'none' | 'loading',
  duration?: number
}

export function modelToast<T extends IModelToast>(options: T) {
  const {title = '', icon = 'none', duration = 2000}: IModelToast = options;
  return Taro.showToast({
    title,
    icon,
    duration,
  });
}

// 防抖 主要bind
// 会重新计时，比如电梯门重新开一次
export function debounce(cb: () => void, wait: number = 0): () => void {
  let timer: NodeJS.Timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(cb.bind(this, ...args), wait)
  }
}

// 节流 主要bind 错误的版本
// 不会重新计时，比如抢券永远取最后一次的点击为准
// export function throttle(cb: () => void, wait: number = 0): () => void {
//   let timer: NodeJS.Timer;
//   return function (...args) {
//     timer = setTimeout(() => {
//       if (timer) clearTimeout(timer);
//       cb.apply(this, args)
//     }, wait)
//   }
// }

// export function throttle()
export function throttle(cb: () => void, wait: number = 0): () => void {
  let timer: NodeJS.Timer;
  return function (...args) {
    if (!timer) {
      timer = setTimeout(() => {
        cb.apply(this, args);
        timer = null;
      }, wait)
    }
  }
}

// 当前页面的按钮点击测试用例
// const button = document.createElement('button');
// button.innerText = '按钮'
// console.log(_, 'lodash')
// window._ = _;
// button.onclick = throttle(function () {
//   console.log('点击', this)
// }, 3000)

// button.onclick = _.debounce(function (){
//   console.log('点击',this)
// },2000)

// document.documentElement.replaceChild(button, document.body);
